<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import { invoke } from "@tauri-apps/api/core";
import { debug } from "@tauri-apps/plugin-log";

const route = useRoute();
const router = useRouter();

// 材料接口定义
interface Material {
    id: number;
    name: string | null;
    code: string | null;
    parent_id: number;
    supplier_id: number | null;
    color_code: string | null;
    background_material: string | null;
    status: number;
    length: number | null;
    width: number | null;
    thickness: number | null;
    residual: number | null;
    price: number | null;
    unit: string | null;
    remark: string | null;
    created_by: string;
    modified_by: string;
    created_at: string;
    modified_at: string;
    is_leaf: boolean | null;
}

// API响应接口
interface ApiResponse<T> {
    status_code: number;
    error_code: number;
    message: string;
    data: T | null;
}

// 判断当前是否为编辑模式
const isEditMode = ref(false);

// 材料详情数据
const materialDetail = ref<Material | null>(null);

// 编辑表单数据
const editForm = ref({
    name: "",
    code: "",
    parent_id: 0,
    supplier_id: null as number | null,
    color_code: "",
    background_material: "",
    status: 1,
    length: null as number | null,
    width: null as number | null,
    thickness: null as number | null,
    residual: null as number | null,
    price: null as number | null,
    unit: "元",
    remark: "",
});

const loading = ref(false);
const error = ref("");
const success = ref("");
const showDeleteConfirm = ref(false);

// 获取材料ID
const materialId = computed(() => {
    return route.params.id ? parseInt(route.params.id as string) : null;
});

// 获取材料详情
async function fetchMaterialDetail() {
    if (!materialId.value) return;

    loading.value = true;
    error.value = "";
    try {
        const response: ApiResponse<Material> = await invoke(
            "material_detail",
            {
                material_id: materialId.value,
            },
        );

        if (response.status_code === 200 && response.data) {
            materialDetail.value = response.data;
            // 将详情数据复制到编辑表单
            Object.assign(editForm.value, response.data);
        } else {
            error.value = response.message || "获取材料详情失败";
        }
    } catch (err) {
        error.value = "网络请求失败";
        console.error("获取材料详情失败:", err);
    } finally {
        loading.value = false;
    }
}

// 进入编辑模式
function enterEditMode() {
    isEditMode.value = true;
}

// 取消编辑
function cancelEdit() {
    isEditMode.value = false;
    // 重置表单数据
    if (materialDetail.value) {
        Object.assign(editForm.value, materialDetail.value);
    }
    error.value = "";
    success.value = "";
}

// 更新材料
async function updateMaterial() {
    if (!materialId.value) return;

    if (!editForm.value.name?.trim()) {
        error.value = "材料名称不能为空";
        return;
    }

    loading.value = true;
    error.value = "";
    success.value = "";

    try {
        debug(`update material json: ${JSON.stringify(editForm.value)}`);
        const response = await invoke("update_material", {
            data: JSON.stringify({
                ...editForm.value,
                id: materialId.value,
            }),
        });

        success.value = "材料更新成功！";

        // 重新获取详情数据
        await fetchMaterialDetail();

        // 退出编辑模式
        isEditMode.value = false;
    } catch (err) {
        error.value = "更新材料失败：" + err;
        console.error("更新材料失败:", err);
    } finally {
        loading.value = false;
    }
}

// 删除材料（软删除，更新状态为0）
async function deleteMaterial() {
    if (!materialId.value) return;

    loading.value = true;
    error.value = "";
    success.value = "";

    try {
        const response = await invoke("update_material", {
            data: JSON.stringify({
                id: materialId.value,
                status: 0, // 设置为0表示删除
                // 保留其他字段不变，只更新状态
                name: materialDetail.value?.name,
                code: materialDetail.value?.code,
                parent_id: materialDetail.value?.parent_id,
                supplier_id: materialDetail.value?.supplier_id,
                color_code: materialDetail.value?.color_code,
                background_material: materialDetail.value?.background_material,
                length: materialDetail.value?.length,
                width: materialDetail.value?.width,
                thickness: materialDetail.value?.thickness,
                residual: materialDetail.value?.residual,
                price: materialDetail.value?.price,
                unit: materialDetail.value?.unit,
                remark: materialDetail.value?.remark,
            }),
        });

        success.value = "材料删除成功！";
        showDeleteConfirm.value = false;

        // 2秒后返回材料列表
        setTimeout(() => {
            router.back();
        }, 2000);
    } catch (err) {
        error.value = "删除材料失败：" + err;
        console.error("删除材料失败:", err);
        showDeleteConfirm.value = false;
    } finally {
        loading.value = false;
    }
}

// 显示删除确认对话框
function confirmDelete() {
    showDeleteConfirm.value = true;
}

// 取消删除
function cancelDelete() {
    showDeleteConfirm.value = false;
}

// 返回上一页
function goBack() {
    router.back();
}

// 价格处理函数
function setPrice(value: number) {
    editForm.value.price = Math.round(value * 10000);
}

function getDisplayPrice() {
    if (!editForm.value.price) return 0;
    return editForm.value.price / 10000;
}

// 页面加载时初始化
onMounted(async () => {
    if (materialId.value) {
        await fetchMaterialDetail();
    } else {
        error.value = "材料ID不存在";
    }
});
</script>

<template>
    <main class="container mx-auto p-4 max-w-4xl">
        <div class="flex justify-between items-center mb-6">
            <h1 class="text-2xl font-bold">
                {{ isEditMode ? "编辑材料" : "材料详情" }}
            </h1>
            <div class="flex gap-2" v-if="!isEditMode">
                <button @click="enterEditMode" class="btn btn-primary">
                    编辑
                </button>
                <button @click="confirmDelete" class="btn btn-error">
                    删除
                </button>
                <button @click="goBack" class="btn btn-outline">返回</button>
            </div>
        </div>

        <!-- 成功提示 -->
        <div v-if="success" class="alert alert-success mb-6">
            <svg
                class="w-6 h-6"
                aria-hidden="true"
                xmlns="http://www.w3.org/2000/svg"
                fill="none"
                viewBox="0 0 24 24"
            >
                <path
                    stroke="currentColor"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="2"
                    d="M8.5 11.5 11 14l4-4m6 2a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"
                />
            </svg>
            <span>{{ success }}</span>
        </div>

        <!-- 错误提示 -->
        <div v-if="error" class="alert alert-error mb-6">
            <svg
                class="w-6 h-6"
                aria-hidden="true"
                xmlns="http://www.w3.org/2000/svg"
                fill="none"
                viewBox="0 0 24 24"
            >
                <path
                    stroke="currentColor"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="2"
                    d="M12 13V8m0 8h0m9-4a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"
                />
            </svg>
            <span>{{ error }}</span>
        </div>

        <!-- 加载状态 -->
        <div v-if="loading" class="text-center p-8">
            <span class="loading loading-spinner loading-lg"></span>
            <p class="mt-2">加载中...</p>
        </div>

        <div
            v-else-if="materialDetail"
            class="bg-base-100 rounded-lg shadow-sm border border-gray-200"
        >
            <!-- 基本信息 -->
            <div class="p-6 border-b border-gray-200">
                <h3 class="text-lg font-semibold text-gray-800 mb-4">
                    基本信息
                </h3>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <!-- 材料名称 -->
                    <div class="form-control">
                        <label class="label">
                            <span class="label-text font-medium">材料名称</span>
                        </label>
                        <input
                            v-if="isEditMode"
                            v-model="editForm.name"
                            type="text"
                            class="input input-bordered"
                            placeholder="请输入材料名称"
                            required
                        />
                        <div v-else class="p-2 border rounded-md bg-gray-50">
                            {{ materialDetail.name || "未命名" }}
                        </div>
                    </div>

                    <!-- 材料编码 -->
                    <div class="form-control">
                        <label class="label">
                            <span class="label-text font-medium">材料编码</span>
                        </label>
                        <input
                            v-if="isEditMode"
                            v-model="editForm.code"
                            type="text"
                            class="input input-bordered"
                            placeholder="请输入材料编码"
                        />
                        <div v-else class="p-2 border rounded-md bg-gray-50">
                            {{ materialDetail.code || "无" }}
                        </div>
                    </div>

                    <!-- 父级材料ID -->
                    <div class="form-control">
                        <label class="label">
                            <span class="label-text font-medium"
                                >父级材料ID</span
                            >
                        </label>
                        <input
                            v-if="isEditMode"
                            v-model="editForm.parent_id"
                            type="number"
                            class="input input-bordered"
                            disabled
                        />
                        <div v-else class="p-2 border rounded-md bg-gray-50">
                            {{ materialDetail.parent_id }}
                        </div>
                        <div
                            class="text-xs text-gray-500 mt-1"
                            v-if="isEditMode"
                        >
                            自动从上级页面获取
                        </div>
                    </div>

                    <!-- 供应商ID -->
                    <div class="form-control">
                        <label class="label">
                            <span class="label-text font-medium">供应商ID</span>
                        </label>
                        <input
                            v-if="isEditMode"
                            v-model="editForm.supplier_id"
                            type="number"
                            class="input input-bordered"
                            placeholder="请输入供应商ID"
                        />
                        <div v-else class="p-2 border rounded-md bg-gray-50">
                            {{ materialDetail.supplier_id || "无" }}
                        </div>
                    </div>

                    <!-- 状态 -->
                    <div class="form-control">
                        <label class="label">
                            <span class="label-text font-medium">状态</span>
                        </label>
                        <select
                            v-if="isEditMode"
                            v-model="editForm.status"
                            class="select select-bordered"
                        >
                            <option :value="1">启用</option>
                            <option :value="0">禁用</option>
                        </select>
                        <div v-else class="p-2 border rounded-md bg-gray-50">
                            <span
                                :class="{
                                    'text-green-600':
                                        materialDetail.status === 1,
                                    'text-red-600': materialDetail.status === 0,
                                }"
                            >
                                {{
                                    materialDetail.status === 1
                                        ? "启用"
                                        : "禁用"
                                }}
                            </span>
                        </div>
                    </div>

                    <!-- 节点类型 -->
                    <div class="form-control" v-if="!isEditMode">
                        <label class="label">
                            <span class="label-text font-medium">节点类型</span>
                        </label>
                        <div class="p-2 border rounded-md bg-gray-50">
                            {{
                                materialDetail.is_leaf === true
                                    ? "叶子节点"
                                    : materialDetail.is_leaf === false
                                      ? "目录节点"
                                      : "目录节点(null)"
                            }}
                        </div>
                    </div>
                </div>
            </div>

            <!-- 尺寸及颜色 -->
            <div class="p-6 border-b border-gray-200">
                <h3 class="text-lg font-semibold text-gray-800 mb-4">
                    尺寸及颜色
                </h3>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <!-- 长度 -->
                    <div class="form-control">
                        <label class="label">
                            <span class="label-text font-medium"
                                >长度（米）</span
                            >
                        </label>
                        <input
                            v-if="isEditMode"
                            v-model="editForm.length"
                            type="number"
                            step="0.001"
                            class="input input-bordered"
                            placeholder="长度"
                        />
                        <div v-else class="p-2 border rounded-md bg-gray-50">
                            {{ materialDetail.length || "无" }}
                        </div>
                    </div>

                    <!-- 宽度 -->
                    <div class="form-control">
                        <label class="label">
                            <span class="label-text font-medium"
                                >宽度（米）</span
                            >
                        </label>
                        <input
                            v-if="isEditMode"
                            v-model="editForm.width"
                            type="number"
                            step="0.001"
                            class="input input-bordered"
                            placeholder="宽度"
                        />
                        <div v-else class="p-2 border rounded-md bg-gray-50">
                            {{ materialDetail.width || "无" }}
                        </div>
                    </div>

                    <!-- 厚度 -->
                    <div class="form-control">
                        <label class="label">
                            <span class="label-text font-medium"
                                >厚度（毫米）</span
                            >
                        </label>
                        <input
                            v-if="isEditMode"
                            v-model="editForm.thickness"
                            type="number"
                            step="0.001"
                            class="input input-bordered"
                            placeholder="厚度"
                        />
                        <div v-else class="p-2 border rounded-md bg-gray-50">
                            {{ materialDetail.thickness || "无" }}
                        </div>
                    </div>

                    <!-- 误差 -->
                    <div class="form-control">
                        <label class="label">
                            <span class="label-text font-medium"
                                >误差（毫米）</span
                            >
                        </label>
                        <input
                            v-if="isEditMode"
                            v-model="editForm.residual"
                            type="number"
                            step="0.001"
                            class="input input-bordered"
                            placeholder="误差"
                        />
                        <div v-else class="p-2 border rounded-md bg-gray-50">
                            {{ materialDetail.residual || "无" }}
                        </div>
                    </div>

                    <!-- 颜色代码 -->
                    <div class="form-control">
                        <label class="label">
                            <span class="label-text font-medium">颜色代码</span>
                        </label>
                        <div class="flex gap-2">
                            <input
                                v-if="isEditMode"
                                v-model="editForm.color_code"
                                class="input input-bordered flex-1"
                                placeholder="颜色代码"
                            />
                            <div
                                v-else
                                class="p-2 border rounded-md bg-gray-50 flex-1"
                            >
                                {{ materialDetail.color_code || "无" }}
                            </div>
                            <div
                                v-if="
                                    isEditMode
                                        ? editForm.color_code
                                        : materialDetail.color_code
                                "
                                class="w-10 h-10 rounded border border-gray-300"
                                :style="{
                                    backgroundColor: isEditMode
                                        ? editForm.color_code
                                        : materialDetail.color_code,
                                }"
                            ></div>
                        </div>
                    </div>

                    <!-- 背面材料 -->
                    <div class="form-control">
                        <label class="label">
                            <span class="label-text font-medium">背面材料</span>
                        </label>
                        <input
                            v-if="isEditMode"
                            v-model="editForm.background_material"
                            class="input input-bordered"
                            placeholder="背面材料"
                        />
                        <div v-else class="p-2 border rounded-md bg-gray-50">
                            {{ materialDetail.background_material || "无" }}
                        </div>
                    </div>
                </div>
            </div>

            <!-- 价格信息 -->
            <div class="p-6 border-b border-gray-200">
                <h3 class="text-lg font-semibold text-gray-800 mb-4">
                    价格信息
                </h3>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <!-- 价格 -->
                    <div class="form-control">
                        <label class="label">
                            <span class="label-text font-medium">价格</span>
                        </label>
                        <div v-if="isEditMode" class="flex gap-2">
                            <input
                                :value="getDisplayPrice()"
                                @input="
                                    setPrice(
                                        parseFloat(
                                            ($event.target as HTMLInputElement)
                                                .value,
                                        ) || 0,
                                    )
                                "
                                type="number"
                                step="0.01"
                                class="input input-bordered flex-1"
                                placeholder="价格"
                            />
                            <select
                                v-model="editForm.unit"
                                class="select select-bordered w-28"
                            >
                                <option value="元">元</option>
                                <option value="美元">美元</option>
                                <option value="欧元">欧元</option>
                                <option value="英镑">英镑</option>
                                <option value="日元">日元</option>
                            </select>
                        </div>
                        <div v-else class="p-2 border rounded-md bg-gray-50">
                            <span v-if="materialDetail.price">
                                {{ materialDetail.price / 10000 }}
                                {{ materialDetail.unit }}
                            </span>
                            <span v-else>无</span>
                        </div>
                        <div
                            class="text-xs text-gray-500 mt-1"
                            v-if="isEditMode"
                        >
                            存储值: {{ editForm.price }} (显示值 × 10000)
                        </div>
                    </div>
                </div>
            </div>

            <!-- 备注信息 -->
            <div class="p-6 border-b border-gray-200">
                <h3 class="text-lg font-semibold text-gray-800 mb-4">
                    备注信息
                </h3>
                <div class="form-control">
                    <textarea
                        v-if="isEditMode"
                        v-model="editForm.remark"
                        class="textarea textarea-bordered h-24"
                        placeholder="请输入备注信息"
                    ></textarea>
                    <div
                        v-else
                        class="p-3 border rounded-md bg-gray-50 min-h-24"
                    >
                        {{ materialDetail.remark || "无备注" }}
                    </div>
                </div>
            </div>
        </div>

        <!-- 编辑模式下的操作按钮 -->
        <div class="flex justify-end gap-3 mt-6" v-if="isEditMode">
            <button
                type="button"
                @click="cancelEdit"
                class="btn btn-outline"
                :disabled="loading"
            >
                取消
            </button>
            <button
                type="button"
                @click="updateMaterial"
                class="btn btn-primary"
                :disabled="loading"
            >
                <span
                    v-if="loading"
                    class="loading loading-spinner loading-sm"
                ></span>
                保存
            </button>
        </div>

        <!-- 删除确认对话框 -->
        <div v-if="showDeleteConfirm" class="modal modal-open">
            <div class="modal-box">
                <h3 class="font-bold text-lg">确认删除</h3>
                <p class="py-4">
                    确定要删除材料 "{{ materialDetail?.name || "未命名" }}"
                    吗？（请谨慎操作！）。
                </p>
                <div class="modal-action">
                    <button
                        @click="cancelDelete"
                        class="btn btn-outline"
                        :disabled="loading"
                    >
                        取消
                    </button>
                    <button
                        @click="deleteMaterial"
                        class="btn btn-error"
                        :disabled="loading"
                    >
                        <span
                            v-if="loading"
                            class="loading loading-spinner loading-sm"
                        ></span>
                        确认删除
                    </button>
                </div>
            </div>
        </div>
    </main>
</template>

<style scoped>
.form-control {
    display: flex;
    flex-direction: column;
}

.label {
    padding: 0;
    margin-bottom: 0.5rem;
}

.label-text {
    font-weight: 500;
    color: #374151;
}
</style>
